package one.stand.util;

import lombok.extern.slf4j.Slf4j;
import one.stand.entity.DynamicPosterEntity;
import one.stand.entity.GoodsPosterEntity;
import one.stand.entity.ImageEntity;
import one.stand.entity.PosterEntity;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.Ellipse2D;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

/**
 * @author: QIK
 * @CreateDate: 2019/4/15 15:06
 */
@Component
@Slf4j
public class ImageGenerateUtil {
    private static String frefix = "png";
    private static String typeface = "Source Han Sans K Bold";

    public static void main(String[] args) throws IOException {
//
////        posterEntity.setImagePath("https://one-stand.oss-cn-shanghai.aliyuncs.com/one-stand/card/card1.png");
////        posterEntity.setCompanyName("〓成都壹立科技有限公司");
////        posterEntity.setEmail("15928444521@163.com");
////        posterEntity.setPhone("15928444521");
////        posterEntity.setCardName("123");
////        posterEntity.setQRCodeUrl("D:/wxcode.png");
////        posterEntity.setCardLogoUrl("D:/userLogo.png");
////        new ImageGenerateUtil().businessCardDraw1(posterEntity);
//
//
//        PosterEntity posterEntity=new PosterEntity();
//        posterEntity.setCardName("张三");
//        posterEntity.setPosition("CTO");
//        posterEntity.setPhone("15928444521");
//        posterEntity.setQRCodeUrl("https://one-stand.oss-cn-shanghai.aliyuncs.com/one-stand/photo/20190427/1556350690486.png");
//        posterEntity.setCardLogoUrl("https://one-stand.oss-cn-shanghai.aliyuncs.com/one-stand/photo/20190730/40eeec23f9cfa0f077793ed9a505abbb.jpg");
//        posterEntity.setCompanyLogo("http://one-stand.oss-cn-shanghai.aliyuncs.com/one-stand/photo/20190619/1560933798596.jpg");
//        posterEntity.setImagePath("http://one-stand.oss-cn-shanghai.aliyuncs.com/one-stand/card/card2.png");
//        posterEntity.setCard2BackUrl("http://one-stand.oss-cn-shanghai.aliyuncs.com/one-stand/card/card2back.png");
//        InputStream inputStream = new ImageGenerateUtil().businessCardDraw2(posterEntity);
//        writeToLocal("D://test.png", inputStream);
//
//        //        PosterEntity posterEntity = new PosterEntity();
////        posterEntity.setQRCodeUrl("D:/wxcode.png");
////        posterEntity.setCardLogoUrl("D:/userLogo.png");
////        posterEntity.setCardName("张三");
////        posterEntity.setEmail("15928444521@163.com");
////        posterEntity.setImagePath("https://one-stand.oss-cn-shanghai.aliyuncs.com/one-stand/card/card3.png");
////        posterEntity.setPhone("15928444521");
////        new ImageGenerateUtil().businessCardDraw3(posterEntity);


        DynamicPosterEntity entity = new DynamicPosterEntity();
        entity.setTitle("AI智能名片，解决企业推广+销售管理两大痛点!");
        entity.setAvatarUrl("https://one-stand.oss-cn-shanghai.aliyuncs.com/one-stand/photo/20191104/cf23526f451784ff137f161b8fe18d5a.png");
        entity.setWxTwoCode("https://one-stand.oss-cn-shanghai.aliyuncs.com/one-stand/photo/20190626/1561546184285.png");
        entity.setAppName("壹脉小程序");
        entity.setDynamicPhoto("https://one-stand.oss-cn-shanghai.aliyuncs.com/one-stand/photo/20190910/8ff817f3a1bf871c6c76a22fcbd0832b.jpg");
        entity.setNickeName("一条酸菜鱼");

        InputStream inputStream2 = new ImageGenerateUtil().getDynamicPosterDraw2(entity);
        writeToLocal("D://test2.png", inputStream2);

    }
    private static void writeToLocal(String destination, InputStream input)
                    throws IOException {
        int index;
        byte[] bytes = new byte[1024];
        FileOutputStream downloadFile = new FileOutputStream(destination);
        while ((index = input.read(bytes)) != -1) {
            downloadFile.write(bytes, 0, index);
            downloadFile.flush();
        }
        downloadFile.close();
        input.close();
    }

    public InputStream getDynamicPosterDraw(DynamicPosterEntity entity) {
        //读取图片文件，得到BufferedImage对象
        try {
            BufferedImage bimg = getUrlByBufferedImage(entity.getBackgroundImg());
            //得到Graphics2D 对象
            Graphics2D g2d = getG2d(bimg);

            // 文章标题
            g2d.setColor(Color.BLACK);
            g2d.setColor(new Color(56,56,56));
            Font font1 = new Font(typeface, Font.BOLD, 16);
            g2d.setFont(font1);
            int titleRowWidth = 240/16 -2;
            List<String> titles = dealRows(entity.getTitle(), titleRowWidth);
            FontMetrics m = g2d.getFontMetrics();
            int fontHeight = m.getAscent() + m.getDescent();
            int titleHeight = 39;
            for (String title : titles){
                g2d.drawString(title, 40, titleHeight);
                titleHeight += fontHeight;
            }
            // 文章封面
            Image dynamicPhoto = getUrlByBufferedImage(entity.getDynamicPhoto());
            g2d.drawImage(dynamicPhoto, 40, 93, 100, 100, null);

            // 太阳码
            Image wxTwoCode = getUrlByBufferedImage(entity.getWxTwoCode());
            g2d.drawImage(wxTwoCode, 160, 93, 100, 100, null);

            // 微信头像
            Image avatarUrl = getUrlByBufferedImage(entity.getAvatarUrl());
            g2d.drawImage(avatarUrl, 40, 214, 40, 40, null);
            // 微信名称
            g2d.setColor(Color.BLACK);
            g2d.setColor(new Color(56,56,56));
            Font font2 = new Font(typeface, Font.PLAIN, 14);
            g2d.setFont(font2);
            g2d.drawString(entity.getNickeName(), 85, 217);
            g2d.setColor(new Color(120,120,120));
            Font font3 = new Font(typeface, Font.PLAIN, 12);
            g2d.setFont(font3);
            g2d.drawString("给您分享了一篇精彩好文", 85, 240);
            // 释放对象
            g2d.dispose();

            return upload(bimg);
        } catch (Exception e) {
            log.info("生成名片海报[异常]", e);
        }

        return null;
    }

    public InputStream getDynamicPosterDraw2(DynamicPosterEntity entity) {
        //读取图片文件，得到BufferedImage对象
        try {
            BufferedImage bimg = getUrlByBufferedImage(entity.getBackgroundImg());
            //得到Graphics2D 对象
            Graphics2D g2d = getG2d(bimg);

            // 文章标题
            g2d.setColor(Color.BLACK);
            g2d.setColor(new Color(56,56,56));
            Font font1 = new Font(typeface, Font.BOLD, 32);
            g2d.setFont(font1);
            int titleRowWidth = 620/32 - 4;
            List<String> titles = dealRows(entity.getTitle(), titleRowWidth);
            FontMetrics m = g2d.getFontMetrics();
            int fontHeight = m.getAscent() + m.getDescent();
            int titleHeight = 78;
            for (String title : titles){
                g2d.drawString(title, 80, titleHeight);
                titleHeight += fontHeight;
            }
            // 文章封面
            Image dynamicPhoto = getUrlByBufferedImage(entity.getDynamicPhoto());
            g2d.drawImage(dynamicPhoto, 80, 186, 200, 200, null);

            // 太阳码
            Image wxTwoCode = getUrlByBufferedImage(entity.getWxTwoCode());
            g2d.drawImage(wxTwoCode, 320, 186, 200, 200, null);

            // 微信头像
            Image avatarUrl = getUrlByBufferedImage(entity.getAvatarUrl());
            g2d.drawImage(avatarUrl, 80, 428, 80, 80, null);
            // 微信名称
            g2d.setColor(Color.BLACK);
            g2d.setColor(new Color(56,56,56));
            Font font2 = new Font(typeface, Font.PLAIN, 28);
            g2d.setFont(font2);
            g2d.drawString(entity.getNickeName(), 170, 450);
            g2d.setColor(new Color(120,120,120));
            Font font3 = new Font(typeface, Font.PLAIN, 24);
            g2d.setFont(font3);
            g2d.drawString("给您分享了一篇精彩好文", 170, 490);
            // 释放对象
            g2d.dispose();

            return upload(bimg);
        } catch (Exception e) {
            log.info("生成名片海报[异常]", e);
        }

        return null;
    }

    /**
     * 生成转转文章海报
     */
    public InputStream getDynamicPosterDraw_bak(DynamicPosterEntity entity){
        //读取图片文件，得到BufferedImage对象
        try {
            BufferedImage bi = new BufferedImage(300, 300, BufferedImage.TYPE_INT_RGB);
            Graphics2D g2d = bi.createGraphics();
            bi = g2d.getDeviceConfiguration().createCompatibleImage(300, 300, Transparency.TRANSLUCENT);
            g2d = bi.createGraphics();
            // 背景
            BufferedImage bimg = getUrlByBufferedImage(entity.getBackgroundImg());
            g2d.drawImage(bimg, 0, 0, 300, 300, null);

            // 文章标题
            g2d.setColor(Color.BLACK);
            g2d.setColor(new Color(56,56,56));
            Font font1 = new Font(typeface, Font.BOLD, 16);
            g2d.setFont(font1);
            int titleRowWidth = 240/16 -2;
            List<String> titles = dealRows(entity.getTitle(), titleRowWidth);
            FontMetrics m = g2d.getFontMetrics();
            int fontHeight = m.getAscent() + m.getDescent();
            int titleHeight = 39;
            for (String title : titles){
                g2d.drawString(title, 40, titleHeight);
                titleHeight += fontHeight;
            }
            // 文章封面
            Image dynamicPhoto = getUrlByBufferedImage(entity.getDynamicPhoto());
            g2d.drawImage(dynamicPhoto, 40, 93, 100, 100, null);

            // 太阳码
            Image wxTwoCode = getUrlByBufferedImage(entity.getWxTwoCode());
            g2d.drawImage(wxTwoCode, 160, 93, 100, 100, null);

            // 微信头像
            Image avatarUrl = getUrlByBufferedImage(entity.getAvatarUrl());
            g2d.drawImage(avatarUrl, 40, 214, 40, 40, null);
            // 微信名称
            g2d.setColor(Color.BLACK);
            g2d.setColor(new Color(56,56,56));
            Font font2 = new Font(typeface, Font.PLAIN, 14);
            g2d.setFont(font2);
            g2d.drawString(entity.getNickeName(), 85, 217);
            g2d.setColor(new Color(120,120,120));
            Font font3 = new Font(typeface, Font.PLAIN, 12);
            g2d.setFont(font3);
            g2d.drawString("给您分享了一篇精彩好文", 85, 240);
            // 释放对象
            g2d.dispose();

            return upload(bi);
        } catch (Exception e) {
            log.info("生成分享文章海报[异常]", e);
        }
        return null;
    }


    // java画图时切割字符串，font就一行显示多少字=控件宽度/字体大小-首尾空格（width/fontSize - 2）
    public static List<String> dealRows(String text, int font){
        text = text.trim();
        StringBuffer sb = new StringBuffer();
        List<String> list = new ArrayList<String>();
        int row = 0;
        int fontSize = font * 2;
        int fontStrSize = 0;
        for (char c : text.toCharArray()) {
            fontStrSize = fontStrSize + 2;
            sb.append(c);
            if (fontSize <= fontStrSize) {
                fontStrSize = 0;
                list.add(sb.toString());
                sb = new StringBuffer();
                row++;
            }
        }
        if(row == 0 || fontStrSize < fontSize){
            list.add(sb.toString());
        }
        return list;
    }
    /**
     * 其中是生成推广的图片的
     */
    public InputStream businessCardDraw1(PosterEntity posterEntity) {
        //读取图片文件，得到BufferedImage对象
        BufferedImage bimg;
        try {

            // 本地使用  bimg = ImageIO.read(new FileInputStream(posterEntity.getImagePath()));
            bimg = getUrlByBufferedImage(posterEntity.getImagePath());
            int w = bimg.getWidth();
            //得到Graphics2D 对象
            Graphics2D g2d = (Graphics2D) bimg.getGraphics();
            // 抗锯齿
            g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            //设置颜色和画笔粗细
            g2d.setColor(Color.WHITE);


            String day = DateUtil.currentDay();
            Font font = new Font(typeface, Font.PLAIN, 120);
            g2d.setFont(font);
            g2d.drawString(day, xPlay(g2d, font, day, w), 410);
            Font font1 = new Font(typeface, Font.PLAIN, 60);

            String month = DateUtil.currentMonth();
            g2d.setFont(font1);
            g2d.drawString(month, xPlay(g2d, font1, month, w), 514);

            String year = (DateUtil.currentYear());
            Font font2 = new Font(typeface, Font.PLAIN, 60);
            g2d.setFont(font2);
            g2d.drawString(year, xPlay(g2d, font2, year, w), 576);

            g2d.setColor(Color.BLACK);
            Font font3 = new Font(typeface, Font.PLAIN, 24);
            g2d.setFont(font3);
            g2d.drawString("〓" + posterEntity.getCompanyName(), 43, 1031);


            Image cardLogo = getUrlByBufferedImage(posterEntity.getCardLogoUrl());
            g2d.drawImage(cardLogo, 40, 1083, 120, 120, null);

            Font font4 = new Font(typeface, Font.BOLD, 36);
            g2d.setFont(font4);
            g2d.drawString(posterEntity.getCardName(), 185, 1083 + 34);


            Font font6 = new Font(typeface, Font.PLAIN, 24);
            g2d.setFont(font6);
            g2d.drawString(posterEntity.getPhone(), 185, 1181 + 23);

//            g2d.setColor(Color.WHITE);
//            String appName =new StringBuffer("-此名片海报由").append(posterEntity.getAppName()).append("生成-").toString();
//            Font font7 = new Font(typeface, Font.PLAIN, 20);
//            g2d.setFont(font2);
//            g2d.drawString(appName, xPlay(g2d, font7, appName, w), 923);


            Image QRCodeImg = getUrlByBufferedImage(posterEntity.getQRCodeUrl());
            g2d.drawImage(QRCodeImg, 465, 990, 245, 245, null);

            // 释放对象
            g2d.dispose();

            return upload(bimg);
        } catch (Exception e) {
            log.info("生成推广的图片[异常]", e);
        }
        return null;
    }

    public InputStream businessCardDraw2(PosterEntity posterEntity) {
        //读取图片文件，得到BufferedImage对象
        try {
            BufferedImage bimg = getUrlByBufferedImage(posterEntity.getImagePath());
            //得到Graphics2D 对象
            Graphics2D g2d = getG2d(bimg);
            int w = bimg.getWidth();

            Image cardLogo = getUrlByBufferedImage(posterEntity.getCardLogoUrl());
            g2d.drawImage(cardLogo, 0, 0, w, 748, null);
            //设置笔刷白色

            Image back = getUrlByBufferedImage(posterEntity.getCard2BackUrl());
            g2d.drawImage(back, 30, 564, 690, 234, null);


            g2d.setColor(Color.BLACK);
            Font font1 = new Font(typeface, Font.BOLD, 36);
            g2d.setFont(font1);
            g2d.drawString(posterEntity.getCardName(), 81, 614 + 34);

            //设置字体灰色
            g2d.setColor(new Color(120, 120, 120));


            Font font2 = new Font(typeface, Font.PLAIN, 28);
            g2d.setFont(font2);
            g2d.drawString(posterEntity.getPosition(), 81, 668 + 26);

            Font font3 = new Font(typeface, Font.PLAIN, 24);
            g2d.setFont(font3);
            g2d.drawString(posterEntity.getPhone(), 134, 731 + 10);

            Image companyId = getUrlByBufferedImage(posterEntity.getCompanyLogo());
            g2d.drawImage(companyId, 556, 622, 120, 120, null);

            Image QRCodeImg = getUrlByBufferedImage(posterEntity.getQRCodeUrl());
            g2d.drawImage(QRCodeImg, 208, 848, 335, 335, null);

//            //#383838
//            Color color=new Color(56,56,56);
//            g2d.setColor(color);
//            String appName =new StringBuffer("-此名片海报由").append(posterEntity.getAppName()).append("生成-").toString();
//            Font font7 = new Font(typeface, Font.PLAIN, 20);
//            g2d.setFont(font2);
//            g2d.drawString(appName, xPlay(g2d, font7, appName, w), 1239);


            // 释放对象
            g2d.dispose();

            return upload(bimg);
        } catch (Exception e) {
            log.info("生成名片海报[异常]", e);
        }

        return null;
    }

    public InputStream businessCardDraw3(PosterEntity posterEntity) {
        try {
            BufferedImage bimg = getUrlByBufferedImage(posterEntity.getImagePath());
            //得到Graphics2D 对象
            Graphics2D g2d = getG2d(bimg);

            Image QRCodeImg = getUrlByBufferedImage(posterEntity.getQRCodeUrl());
            g2d.drawImage(QRCodeImg, 252, 283, 245, 245, null);

            Image cardLogo = getUrlByBufferedImage(posterEntity.getCardLogoUrl());
            g2d.drawImage(cardLogo, 315, 934, 120, 120, null);
            //设置字体颜色
            g2d.setColor(Color.WHITE);

            Font font1 = new Font(typeface, Font.PLAIN, 33);
            g2d.setFont(font1);
            g2d.drawString(posterEntity.getCardName(), xPlay(g2d, font1, posterEntity.getCardName(), bimg.getWidth()), 1087 + 32);


            Font font2 = new Font(typeface, Font.PLAIN, 24);
            g2d.setFont(font2);
            g2d.drawString(posterEntity.getPhone(), xPlay(g2d, font2, posterEntity.getPhone(), bimg.getWidth()), 1148 + 20);

            g2d.drawString(posterEntity.getEmail(), xPlay(g2d, font2, posterEntity.getEmail(), bimg.getWidth()), 1183 + 20);


//            int w = bimg.getWidth();
//            g2d.setColor(Color.WHITE);
//            String appName =new StringBuffer("-此名片海报由").append(posterEntity.getAppName()).append("生成-").toString();
//            Font font7 = new Font(typeface, Font.PLAIN, 20);
//            g2d.setFont(font2);
//            g2d.drawString(appName, xPlay(g2d, font7, appName, w), 802);

            // 释放对象
            g2d.dispose();


            return upload(bimg);
        } catch (Exception e) {
            log.info("生成名片海报[异常]", e);
        }

        return null;
    }

    /**
     * 商品卡片
     *
     * @return
     */
    public InputStream goodsCard(GoodsPosterEntity goodsPosterEntity) {
        try {
            BufferedImage bimg = getUrlByBufferedImage(goodsPosterEntity.getImagePath());
            //得到Graphics2D 对象
            Graphics2D g2d = getG2d(bimg);
            int w = bimg.getWidth();
            Image goodsImg = getUrlByBufferedImage(goodsPosterEntity.getGoodsUrl());
            g2d.drawImage(goodsImg, 0, 0, w, 750, null);

            //设置字体红色
            g2d.setColor(new Color(253, 99, 78));
            String moneyText = "￥" + goodsPosterEntity.getMoney();
            g2d.setFont(new Font(typeface, Font.PLAIN, 60));
            g2d.drawString(moneyText, 51, 750 + 71 + 51);

            g2d.setColor(new Color(56, 56, 56));
            String goodsName = goodsPosterEntity.getGoodsName();
            Font font1 = new Font(typeface, Font.PLAIN, 36);
            g2d.setFont(font1);
            g2d.drawString(goodsName, 70, 750 + 184 + 21);

            Image userLogo = getUrlByBufferedImage(goodsPosterEntity.getUserLogo());
            g2d.drawImage(userLogo, 50, 284 + 750 + 75, 100, 100, null);


            Image sunCodeUrl = getUrlByBufferedImage(goodsPosterEntity.getSunCodeUrl());
            g2d.drawImage(sunCodeUrl, 450, 284 + 750, 250, 250, null);


            g2d.setColor(new Color(168, 168, 168));
            String userName = goodsPosterEntity.getUserName();
            Font font2 = new Font(typeface, Font.PLAIN, 28);
            g2d.setFont(font2);
            g2d.drawString(userName, 170, 750 + 371 + 24);

            g2d.drawString("推荐您看", 169, 750 + 420 + 26);
            // 释放对象
            g2d.dispose();

            return upload(bimg);
        } catch (Exception c) {
            c.printStackTrace();
        }
        return null;
    }

    public InputStream image(ImageEntity imageEntity) {
        log.info("开始生成图片：{}",imageEntity.toString());
        try {
            BufferedImage   image = getUrlByBufferedImage(imageEntity.getParam());
            int w = image.getWidth();
            int h=image.getHeight();

            BufferedImage bimg = new BufferedImage(w, h,BufferedImage.TYPE_INT_RGB);

            //得到Graphics2D 对象
            Graphics2D g2d = getG2d(bimg);
            g2d.drawImage(image, 0, 0, w, h,null);

            recursion(imageEntity.getImageEntityList(),g2d,w,h);


            // 释放对象
            g2d.dispose();

            return upload(bimg);
        } catch (Exception e) {
            log.info("生成图片[异常]", e);
        }
        return null;
    }

    /**
     * 图片设置圆角
     * @param srcImage
     * @return
     * @throws IOException
     */
    public static BufferedImage setRadius(BufferedImage srcImage,int header) throws IOException{
        int radius = (srcImage.getWidth() + srcImage.getHeight()) / 6;
        return setRadius(srcImage, radius, 1, 3,header);
    }

    public void recursion( List<ImageEntity> imageEntityList,Graphics2D g2d ,int w,int h) throws IOException {
        for (ImageEntity e:imageEntityList) {
            if (e.getType() == 1) {
                if(StringUtils.isBlank(e.getParam())){
                    log.info("参数为空：跳过当前循环{}",e.toString());
                    continue;
                }
                if (null != e.getColor()) {
                    g2d.setColor(e.getColor());
                }
                Font font = new Font(e.getTypeface(), e.getPlain(), e.getSize());
                g2d.setFont(font);
                if (e.getCentered()) {
                    g2d.drawString(e.getParam(), xPlay(g2d, font, e.getParam(), w), e.getYAxis());
                } else {
                    g2d.drawString(e.getParam(), e.getXAxis(), e.getYAxis());
                }
            }
            if (e.getType() == 2) {
                BufferedImage drawImage = getUrlByBufferedImage(e.getParam());
                if(e.getHeader() == 2 || e.getHeader() == 3){
                    drawImage = setRadius(drawImage,e.getHeader());
                }
                g2d.drawImage(drawImage, e.getXAxis(), e.getYAxis(), e.getWidth(), e.getHigh(),null);
            }
            if(e.getType()==3){
                //RGB形式
                BufferedImage bi = new BufferedImage(e.getWidth(), e.getHigh(), BufferedImage.TYPE_INT_RGB);
                //得到Graphics2D 对象
                Graphics2D g = getG2d(bi);
                g.setColor(e.getColor());
                g.fillRect(0, 0, e.getWidth(), e.getHigh());
                g2d.drawImage(bi, e.getXAxis(), e.getYAxis(), e.getWidth(), e.getHigh(),null);
                if(null!=e.getImageEntityList()){
                    log.info("检测到还有子级");
                    recursion(e.getImageEntityList(),g,e.getWidth(), e.getHigh());
                }
                g.dispose();

            }
        }
    }

    /**
     * 图片设置圆角
     * @param srcImage
     * @param radius
     * @param border
     * @param padding
     * @return
     * @throws IOException
     */
    public static BufferedImage setRadius(BufferedImage srcImage, int radius, int border, int padding,int header) throws IOException{
        int width = srcImage.getWidth();
        int height = srcImage.getHeight();
        int canvasWidth = width + padding * 2;
        int canvasHeight = height + padding * 2;

        BufferedImage image = new BufferedImage(canvasWidth, canvasHeight, BufferedImage.TYPE_INT_ARGB);
        Graphics2D gs = image.createGraphics();
        gs.setComposite(AlphaComposite.Src);
        gs.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        gs.setColor(Color.WHITE);
        gs.fill(new RoundRectangle2D.Float(0, 0, canvasWidth, canvasHeight, radius, radius));
        gs.setComposite(AlphaComposite.SrcAtop);
        if(header == 3){
            gs.drawImage(setClipRound(srcImage, radius), padding, padding, null);
        }else{
            gs.drawImage(setClip(srcImage, radius), padding, padding, null);
        }
        if(border !=0){
            gs.setColor(Color.GRAY);
            gs.setStroke(new BasicStroke(border));
            gs.drawRoundRect(padding, padding, canvasWidth - 2 * padding, canvasHeight - 2 * padding, radius, radius);
        }
        gs.dispose();
        return image;
    }
    /**
     * 图片切圆角
     * @param srcImage
     * @param radius
     * @return
     */
    public static BufferedImage setClip(BufferedImage srcImage, int radius){
        int width = srcImage.getWidth();
        int height = srcImage.getHeight();
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
        Graphics2D gs = image.createGraphics();

        gs.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        gs.setClip(new RoundRectangle2D.Double(0, 0, width, height, radius, radius));
        gs.drawImage(srcImage, 0, 0, null);
        gs.dispose();
        return image;
    }
    public static BufferedImage setClipRound(BufferedImage srcImage, int radius){
        int width = srcImage.getWidth();
        int height = srcImage.getHeight();
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
        Graphics2D gs = image.createGraphics();
        int border = 1;
        gs.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        int temp1 = width - border * 2;
        gs.setClip(new Ellipse2D.Double(0, 0, temp1, temp1));
        gs.drawImage(srcImage, 0, 0, null);
        gs.dispose();
        return image;
    }

    /**
     * 通过网络获取图片
     *
     * @param url
     * @return
     */
    public static BufferedImage getUrlByBufferedImage(String url) {
        try {
            URL urlObj = new URL(url);
            HttpURLConnection conn = (HttpURLConnection) urlObj.openConnection();
            // 连接超时
            conn.setDoInput(true);
            conn.setDoOutput(true);
            conn.setConnectTimeout(25000);
            // 读取超时 --服务器响应比较慢,增大时间
            conn.setReadTimeout(25000);
            conn.setRequestMethod("GET");
            conn.addRequestProperty("Accept-Language", "zh-cn");
            conn.addRequestProperty("Content-type", "image/png");
            conn.addRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; .NET CLR 2.0.50727)");
            conn.connect();
            BufferedImage bufImg = ImageIO.read(conn.getInputStream());
            conn.disconnect();
            return bufImg;
        } catch (IOException e) {
            log.info("通过网络获取图片[系统繁忙]", e);
        }
        return null;
    }

    private Graphics2D getG2d(BufferedImage bimg) {
        //得到Graphics2D 对象
        Graphics2D g2d = (Graphics2D) bimg.getGraphics();
        // 抗锯齿
        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        return g2d;
    }

    private static int xPlay(Graphics2D g2d, Font font, String text, int w) {
        FontMetrics fm = g2d.getFontMetrics(font);
        int textWidth = fm.stringWidth(text);
        return (w - textWidth) / 2;

    }

    public InputStream upload(BufferedImage bimg) throws IOException {
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        //保存新图片
        ImageIO.write(bimg, frefix, os);
        InputStream is = new ByteArrayInputStream(os.toByteArray());
        return is;
    }
}
